﻿using System;
using System.Windows.Forms;
using HighDiveAdmin.GUI;
using HighDiveAdmin.Engine;
using HighDiveAdmin.Handlers;
using HighDiveEngine.Resources;

[assembly: log4net.Config.XmlConfigurator(ConfigFile ="log4net.config", Watch = true)]

namespace HighDiveAdmin
{    
    static class Program
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        [STAThread]
        static void Main()
        {
            //var customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            //customCulture.NumberFormat.NumberDecimalSeparator = ".";
            Log.Info("Program Starting");
            FormMain formMain = null;
            HighDiveAdminEngine contestEngine = null;
            FormMainPresenter formMainPresenter = null;

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                formMain = new FormMain();
                contestEngine = new HighDiveAdminEngine();
                formMainPresenter = new FormMainPresenter(contestEngine, formMain);
                Application.Run(formMain);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                if (contestEngine != null)
                {
                    if (contestEngine.Contest != null)
                    {
                        if (contestEngine.Contest.JudgeList != null)
                        {
                            foreach (var judge in contestEngine.Contest.JudgeList)
                            {
                                lock (judge.Status)
                                {
                                    if (judge.Status.Equals(JudgeStatus.Status.Connected) || judge.Status.Equals(JudgeStatus.Status.SlowReply))
                                        TcpHandler.Instance.SendMessage(judge.IpAdress + "@AdminAppExited"); 
                                }
                            } 
                        }
                    } 
                }
            }
            Log.Info("Program Exiting");
        }
    }
}
